package cn.ipanel.bigdata.boot.date

/**
 * Author: lzz
 * Date: 2021/11/23 9:26
 */
case class Year(st: Long, et: Long, len: Int) extends Date(st, et) {

  override def prev(n: Int = 1): Year = {
    var m: Year = this
    for (_ <- 1 to n)
      m = Year(m.st - Date.DAY_TIME)
    m
  }

  override def next(n: Int = 1): Year = {
    var m: Year = this
    for (_ <- 1 to n)
      m = Year(m.et + Date.DAY_TIME + 1)
    m
  }

  lazy final val minDayYear: Int = 0
  lazy final val maxDayYear: Int = len - 1
  lazy final val lenDayYear: Int = maxDayYear + 1

  def getMonth(n: Int): Month = {
    if (n < 0) null
    else if (n > 11) null
    else {
      val ca: java.util.Calendar = java.util.Calendar.getInstance()
      ca.setTime(new java.util.Date(st))
      ca.set(java.util.Calendar.MONTH, n)
      Month(ca.getTime.getTime)
    }
  }

  def getQuarter(n: Int): Quarter = {
    n match {
      case 0 => Quarter(getMonth(2).st)
      case 1 => Quarter(getMonth(5).st)
      case 2 => Quarter(getMonth(8).st)
      case 3 => Quarter(getMonth(11).st)
      case _ => null
    }
  }

  def getDay(n: Int): Day = {
    if (n < minDayYear) null
    else if (n > maxDayYear) null
    else Day(st + Date.DAY_TIME * n)
  }

  override def toString: String = s"Year(${STime.toYYYYMMddHHmmss} To ${ETime.toYYYYMMddHHmmss})"
}

object Year {

  def unapply(yyyyMMdd: String): Option[(Long, Long, Int)] = {
    unapply(Time(yyyyMMdd).time)
  }

  def unapply(time: Long): Option[(Long, Long, Int)] = {
    val ca: java.util.Calendar = java.util.Calendar.getInstance();
    ca.setTime(new java.util.Date(time))
    ca.set(java.util.Calendar.HOUR_OF_DAY, 0)
    ca.set(java.util.Calendar.MINUTE, 0)
    ca.set(java.util.Calendar.SECOND, 0)
    ca.set(java.util.Calendar.MILLISECOND, 0)
    val min: Int = ca.getActualMinimum(java.util.Calendar.DAY_OF_YEAR)
    ca.set(java.util.Calendar.DAY_OF_YEAR, min)
    val st: Long = ca.getTime.getTime
    val max: Int = ca.getActualMaximum(java.util.Calendar.DAY_OF_YEAR)
    ca.set(java.util.Calendar.DAY_OF_YEAR, max)
    val et: Long = ca.getTime.getTime
    Some(st, et + Date.DAY_TIME - 1, max)
  }

  def apply(yyyyMMdd: String): Year = apply(Time(yyyyMMdd))
  def apply(time: Time): Year = apply(time.time)
  def apply(time: Long): Year = time match {
    case Year(st, et, len) => Year(st, et, len)
    case _ => null
  }
}